package com.summer.bilibili.validator.asserts;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 验证一个对象的值是否在指定的字符串数组中
 */
public class AssertValidator implements ConstraintValidator < Assert, Object > {

    // 使用HashSet优化查询性能
    private Set<String> forbiddenValues;

    @Override
    public void initialize(Assert constraintAnnotation) {
        // 将数组转为HashSet (O(1)查询复杂度)
        forbiddenValues = new HashSet <> ( Arrays.asList(constraintAnnotation.value()));
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 保留原空值处理逻辑：允许null值
        if (value == null) {
            return true;
        }
       // 字符串比较
        String stringValue = value.toString();

        // 存在非法值返回false
        return !forbiddenValues.contains ( stringValue );
    }
}
